﻿using System;
using System.Collections.Generic;
using System.Text;

using Obsidian.Action;
using Oak.Base;
using Oak.Model;
using Oak.MagSys.Logic;

namespace Oak.MagSys.Serv
{
    public class FrameServ : OakServ<ISession>
    {

        private const string FN_FRAME = "frameId,title,url,ico,options";

        public FrameServ(ISession session) : base(session) { }

        public void List(ActionRequest req, ActionResponse res)
        {

            if (!Session.IsLogin)
            {
                res.SessionInvalid();
                return;
            }

            MsFrameQry qry = req.FirstModel<MsFrameQry>();
            string msg;
            FrameLG frameLG = new FrameLG(Session);
            List<MsFrameInfo> list = frameLG.GetFrameList(qry, out msg);

            if (list == null)
            {
                res.Error(msg);
                return;
            }

            res.AddResult("frames", FN_FRAME, list);
        }

        public void Add(ActionRequest req, ActionResponse res)
        {
            if (!Session.IsAdmin)
            {
                res.SessionInvalid();
                return;
            }

            MsFrameInfo frame = req.FirstModel<MsFrameInfo>();

            string msg;
            FrameLG frameLG = new FrameLG(Session);
            frame = frameLG.AddFrame(frame, out msg);

            if (frame == null)
            {
                res.Error(msg);
                return;
            }

            res.AddResult("frames", FN_FRAME, frame);
        }

        public void Update(ActionRequest req, ActionResponse res)
        {
            if (!Session.IsAdmin)
            {
                res.SessionInvalid();
                return;
            }

            MsFrameInfo frame = req.FirstModel<MsFrameInfo>();
            string msg;
            FrameLG frameLG = new FrameLG(Session);
            frame = frameLG.UpdateFrame(frame, out msg);

            if (frame == null)
            {
                res.Error(msg);
                return;
            }

            res.AddResult("frames", FN_FRAME, frame);

        }

        public void Delete(ActionRequest req, ActionResponse res)
        {
            if (!Session.IsAdmin)
            {
                res.SessionInvalid();
                return;
            }

            long frameId;
            if (!req.TryGetLong("frameId", out frameId))
            {
                res.Error("参数frameId错误");
                return;
            }

            string msg;
            FrameLG frameLG = new FrameLG(Session);
            bool succ = frameLG.DeleteFrame(frameId, out msg);
            if (!succ)
            {
                res.Error(msg);
                return;
            }
        }
    }
}
